package com.tangkun.environment.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
import com.tangkun.environment.R;
import com.tangkun.environment.application.Session;
import com.tangkun.environment.entity.base.CommonReturn;
import com.tangkun.environment.entity.personcenter.UploadResourceReturn;
import com.tangkun.environment.entity.token.LoginReturn;
import com.tangkun.environment.network.GlobalUrl;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.utils.DownLoadImageService;
import com.tangkun.environment.utils.ImageDownLoadCallBack;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.SharePrefercesUtils;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.CircleImageView;
import com.tangkun.environment.view.CommonDialog;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * 个人资料
 */

public class GeRenZiLiaoActivity extends BaseActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.iv_perfect_infomation_headimg)
    CircleImageView ivPerfectInfomationHeadimg;
    @BindView(R.id.et_perfect_infomation_name)
    EditText etPerfectInfomationName;
    @BindView(R.id.ll_perfect_infomation_name)
    LinearLayout llPerfectInfomationName;
    @BindView(R.id.rb_perfect_infomation_xingbie_nan)
    RadioButton rbPerfectInfomationXingbieNan;
    @BindView(R.id.rb_perfect_infomation_xingbie_nv)
    RadioButton rbPerfectInfomationXingbieNv;
    @BindView(R.id.rg_perfect_infomation_xingbie)
    RadioGroup rgPerfectInfomationXingbie;
    @BindView(R.id.tv_perfect_infomation_shoujihao)
    TextView tvPerfectInfomationShoujihao;
    @BindView(R.id.ll_perfect_infomation_shoujihao)
    LinearLayout llPerfectInfomationShoujihao;
    @BindView(R.id.ll_perfect_infomation_xiugaimima)
    LinearLayout llPerfectInfomationXiugaimima;

    private Context mContext;
    private PopupWindow popupWindow;
    private final int REQUEST_CODE_PICK_IMAGE = 10;
    private final int REQUEST_CODE_CAPTURE_CAMEIA = 11;
    private final int REQUEST_CODE_CROP_IMAGE = 12;

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private Uri tmpUri;
    private String tmpPath;
    /**
     * 性别 0男 1女
     */
    private int sex = 0;


    private static final int IMAGE_W = 400;
    private static final int IMAGE_H = 200;
    /**
     * 最大图片上传张数
     */
    private static final int IMAGE_NUM_ = 1;
    /**
     * // 请求码
     */
    public static final int REQUEST_CODE_ = 1;
    /**
     * 本地图片
     */
    private List<File> fileList = new ArrayList<File>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_gerenziliao);
        ButterKnife.bind(this);
        title.setText("个人资料");
        initData();
        initLisener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        //头像
        Glide.with(GeRenZiLiaoActivity.this)
                .load(GlobalUrl.IMG_URL + Session.getInstance().getUserHeadPicture())
                .bitmapTransform(new CropCircleTransformation(GeRenZiLiaoActivity.this))
                .placeholder(R.mipmap.ic_wrong_head)
                .dontAnimate()
                .into(ivPerfectInfomationHeadimg);
        //昵称
        etPerfectInfomationName.setText(Session.getInstance().getUserNickName());
        etPerfectInfomationName.setCursorVisible(false);//隐藏光标
        //将监听时间赋给父控件
        etPerfectInfomationName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                llPerfectInfomationName.performClick();
            }
        });
        //手机号
        tvPerfectInfomationShoujihao.setText(Session.getInstance().getUserName());
        //性别
        if ((Session.getInstance().getUserSex()).equals("男")) {
            rbPerfectInfomationXingbieNan.setChecked(true);
        } else {
            rbPerfectInfomationXingbieNv.setChecked(true);
        }

        //初始化临时路径
        tmpUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
    }

    private void initLisener() {
        //性别控件监听事件
        rgPerfectInfomationXingbie.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                //更新用户性别
                Map<String, String> map = new HashMap<String, String>();
                switch (i) {
                    case R.id.rb_perfect_infomation_xingbie_nan:
                        //更新用户性别 男
                        map.put("sex", "man");
                        updateUser(map, 1);
                        break;
                    case R.id.rb_perfect_infomation_xingbie_nv:
                        //更新用户性别 女
                        map.put("sex", "female");
                        updateUser(map, 1);
                        break;
                }
            }
        });
    }

    @OnClick({R.id.back, R.id.iv_perfect_infomation_headimg, R.id.ll_perfect_infomation_name, R.id.ll_perfect_infomation_shoujihao, R.id.ll_perfect_infomation_xiugaimima, R.id.btn_perfect_infomation_tuichudenglu})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back://返回按钮
                Utils.hideSoftKeyboard(GeRenZiLiaoActivity.this, back);
                JumpHelper.finish(GeRenZiLiaoActivity.this);
                break;
            case R.id.iv_perfect_infomation_headimg://头像
//                bottomWindow(back);
//                backgroundAlpha(0.5f);
                openXiangce();
                break;
            case R.id.ll_perfect_infomation_name://昵称
                Intent nickNameIntent = new Intent(GeRenZiLiaoActivity.this, ModifyNickNameActivity.class);
                nickNameIntent.putExtra("content", Session.getInstance().getUserNickName());//用户昵称
                JumpHelper.jumpForResult(GeRenZiLiaoActivity.this, nickNameIntent, 1000, false);
                break;
            case R.id.ll_perfect_infomation_shoujihao://手机号
                JumpHelper.jump(GeRenZiLiaoActivity.this, XiuGaiShouJiActivity.class, false);
                break;
            case R.id.ll_perfect_infomation_xiugaimima://修改密码
                JumpHelper.jump(GeRenZiLiaoActivity.this, XiuGaiMiMaActivity.class, false);
                break;
            case R.id.btn_perfect_infomation_tuichudenglu://退出登录
                showLoginoutDialog();
                break;
        }
    }

    /**
     * 打开相册
     */
    private void openXiangce() {
        Intent intent = new Intent(GeRenZiLiaoActivity.this, CaptureImageActivity.class);
        intent.putExtra("w", IMAGE_W);
        intent.putExtra("h", IMAGE_H);
        intent.putExtra("custom", false);
        intent.putExtra("module", "weibo");
        intent.putExtra("num", IMAGE_NUM_);
        intent.putExtra("isShowOriginal", false);
        startActivityForResult(intent, REQUEST_CODE_);
    }

    /**
     * 退出登录对话框
     */
    private void showLoginoutDialog() {
        CommonDialog commonDialog = new CommonDialog(GeRenZiLiaoActivity.this, "退出登录", "确定要退出登录吗？");
        commonDialog.show();
        commonDialog.setOnClickListener(new CommonDialog.OnClickListener() {
            @Override
            public void leftClick() {//取消

            }

            @Override
            public void rightClick() {//确认
                logout();
            }
        });
    }

    /**
     * 退出登录 注销登陆
     */
    private void logout() {
        fromNetwork.loginout().compose(new RxActivityHelper<CommonReturn>().ioMain(GeRenZiLiaoActivity.this, true))
                .subscribe(new MySubscribe<CommonReturn>(mContext, true) {

                    @Override
                    protected void success(CommonReturn result) {
                        //清除Session
                        Session.getInstance().destroy();
                        //清除SharedPreference
                        SharePrefercesUtils.clear();
                        //跳转主页面
                        JumpHelper.jump(GeRenZiLiaoActivity.this, LoginActivity.class, true);
                        //发出通知刷新主页面
                        EventBus.getDefault().post(true, "MainActivity.refreshFragment");
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }

    private void bottomWindow(View view) {
        if (popupWindow != null && popupWindow.isShowing()) {
            return;
        }
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.person_photo_popuwindows, null);
        popupWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //点击空白处时，隐藏掉pop窗口
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
        popupWindow.setAnimationStyle(R.style.Popupwindow);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.BOTTOM, 0, -location[1]);
        //添加按键事件监听
        setListeners(layout);
        //添加pop窗口关闭事件，主要是实现关闭时改变背景的透明度
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
    }

    /**
     * popuwindows的监听事件
     *
     * @param layout
     */
    private void setListeners(LinearLayout layout) {
        TextView takePhoto = (TextView) layout.findViewById(R.id.takePhoto);
        TextView fromXiangCe = (TextView) layout.findViewById(R.id.from_xiangCe);
        TextView savepicture = (TextView) layout.findViewById(R.id.save_img);
        TextView cancel = (TextView) layout.findViewById(R.id.cancle_geRenTouXiang);

        //拍照
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    //调用系统相机拍照
                    popupWindow.dismiss();
                    makePhoto();
                }
            }
        });
        //相册
        fromXiangCe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    //在此处添加你的按键处理
                    popupWindow.dismiss();
                    takePhoto();
                }
            }
        });
        //保存图片
        savepicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    //在此处添加你的按键处理 xxx
                    popupWindow.dismiss();
                    //头像图片网络地址
                    String url = Session.getInstance().getResourceBaseUrl() + Session.getInstance().getUserHeadPicture();
                    //下载图片线程
                    DownLoadImageService downLoadImageService = new DownLoadImageService(mContext, url, new ImageDownLoadCallBack() {
                        @Override
                        public void onDownLoadSuccess(File file) {

                        }

                        @Override
                        public void onDownLoadSuccess(Bitmap bitmap) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showToast("保存成功");
                                }
                            });
                        }

                        @Override
                        public void onDownLoadFailed() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showToast("保存失败");
                                }
                            });
                        }
                    });
                    //启动图片下载线程
                    new Thread(downLoadImageService).start();
                }
            }
        });
        //取消
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    private static Uri getOutputMediaFileUri(int type) {
        File file = getOutputMediaFile(type);
        if (file == null) {
            return null;
        }
        return Uri.fromFile(file);
    }

    private static File getOutputMediaFile(int type) {
        if (!Utils.isSDState()) {
            return null;
        }
        File mediaStoreaDir = new File(Environment.getExternalStorageDirectory(), "EnvironmentApp");
        if (!mediaStoreaDir.exists()) {
            if (!mediaStoreaDir.mkdirs()) {
                return null;
            }
        }
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStoreaDir.getPath() + File.separator + "IMG_TEMP" + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStoreaDir.getPath() + File.separator + "VID_TIMP" + ".mp4");
        } else {
            return null;
        }
        if (mediaFile.exists()) {
            try {
                mediaFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mediaFile;
    }

    /**
     * 拍照
     */
    private void makePhoto() {
        if (tmpUri == null) {
            showToast("请插入内存卡");
            return;
        }
        final Intent intentTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intentTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, tmpUri);
        intentTakePhoto.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
        startActivityForResult(intentTakePhoto, REQUEST_CODE_CAPTURE_CAMEIA);
    }

    /**
     * 从相册选取
     */
    private void takePhoto() {
        Intent intentPic = new Intent();
        intentPic.setType("image/*");
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
//            intentPic.setAction(Intent.ACTION_GET_CONTENT);
//        } else {
//            intentPic.setAction(Intent.ACTION_OPEN_DOCUMENT);
//            intentPic.addCategory(Intent.CATEGORY_OPENABLE);
//        }
        intentPic.setAction(Intent.ACTION_GET_CONTENT);
        intentPic.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(Intent.createChooser(intentPic, "头像选择"), REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 刷新来自相册列表选中的图片列表 
        if (requestCode == REQUEST_CODE_ && resultCode == CaptureImageActivity.CAPTURE) {
            List<File> list = (List<File>) data.getSerializableExtra("fileList");
            if (list != null) {
                fileList.clear();
                fileList.addAll(list);
                if (fileList != null && fileList.size() > 0) {
                    sendPhotoToServer((fileList.get(0)).getPath());
                }
            }
        }

//        if (resultCode == RESULT_OK) {
//            if (requestCode == REQUEST_CODE_PICK_IMAGE) {
//                // 从相册取图片
//                if (data != null) {
//                    if (data.getData() != null) {
//                        Uri uri = data.getData();
//                        String string = Utils.getPath(this, uri);
//                        if (string != null && !"".equals(string)) {
//                            System.gc();
//                            Intent intent = new Intent();
//                            intent.setClass(this, CropImageActivity.class);
//                            intent.putExtra("uri", string);
//                            startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
//                        } else {
//                            showToast("获取照片失败");
//                        }
//                    } else {
//                        showToast("获取照片失败");
//                    }
//                }
//            } else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA) {
//                // 拍照
//                if (tmpUri == null) {
//                    tmpUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
//                }
//                String string = Utils.getPath(this, tmpUri);
//                if (string != null && !"".equals(string)) {
//                    System.gc();
//                    Intent intent = new Intent();
//                    intent.setClass(this, CropImageActivity.class);
//                    intent.putExtra("uri", string);
//                    startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
//                } else {
//                    showToast("获取照片失败");
//                }
//            } else if (requestCode == REQUEST_CODE_CROP_IMAGE) {
//                tmpPath = data.getStringExtra("backurl");
//                if (tmpPath != null) {
//                    //上传服务器
//                    LogUtils.e("图片地址：" + tmpPath);
//                    sendPhotoToServer(tmpPath);
//                } else {
//                    showToast("返回裁剪图片出错");
//                }
//            }
//        }
    }

    /**
     * 上传图片到服务器
     *
     * @param filePath 本地图片路径
     */
    private void sendPhotoToServer(String filePath) {
        String[] filePathArray = filePath.split("/");
        //文件名
        String fileName = filePathArray[filePathArray.length - 1];
        //生成文件
        File file = new File(filePath);
        //组装partMap对象
        Map<String, RequestBody> partMap = new HashMap<>();
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);//文件
//        partMap.put("file", fileBody);//文件名
        partMap.put("file\"; filename=\"" + fileName + "", fileBody);//文件名
//        RequestBody dirBody = RequestBody.create(MediaType.parse("text/plain"), "user/header");//dir参数值
//        RequestBody fileNameBody = RequestBody.create(MediaType.parse("text/plain"), fileName);//文件名参数值
//        partMap.put("dir", dirBody);//dir参数
//        partMap.put("fileName", fileNameBody);//dir参数
        fromNetwork.uploadImageUser(partMap).compose(new RxActivityHelper<UploadResourceReturn>().ioMain(GeRenZiLiaoActivity.this, true))
                .subscribe(new MySubscribe<UploadResourceReturn>(mContext, true) {
                    @Override
                    protected void success(UploadResourceReturn uploadResourceReturn) {
                        if (uploadResourceReturn.data != null) {
                            if (uploadResourceReturn.data.size() > 0) {
                                //上传头像地址
                                String headPicture = uploadResourceReturn.data.get(0).url;
                                //更新用户头像
                                Map<String, String> map = new HashMap<String, String>();
                                map.put("img", headPicture);
                                updateUser(map, 0);
                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }

    /**
     * 更新个人信息
     *
     * @param map  参数键值对
     * @param type 类型 0头像  1性别
     */
    private void updateUser(Map<String, String> map, final int type) {
        fromNetwork.updateUser(map).compose(new RxActivityHelper<LoginReturn>().ioMain(GeRenZiLiaoActivity.this, true))
                .subscribe(new MySubscribe<LoginReturn>(mContext, true) {
                    @Override
                    protected void success(final LoginReturn resultBean) {
                        if (resultBean.data != null) {
                            switch (type) {
                                case 0://0头像
                                    //更改头像
                                    Session.getInstance().getUserInfo().img = resultBean.data.img;
                                    //圆形裁剪
                                    Glide.with(mContext)
                                            .load(GlobalUrl.IMG_URL + resultBean.data.img)
                                            .bitmapTransform(new CropCircleTransformation(mContext))
                                            .placeholder(R.mipmap.ic_wrong_head)
                                            .dontAnimate()
                                            .into(ivPerfectInfomationHeadimg);
                                    break;
                                case 1://1性别
                                    //更改性别
                                    Session.getInstance().getUserInfo().sex = resultBean.data.sex;
                                    break;
                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }
}
